package com.itmate.dao;

import com.itmate.db.DBUtil;
import com.itmate.entity.Users;

import java.util.ArrayList;
import java.util.List;

public class UsersDao extends BaseDao {

	/**
	 * 判断账号密码是否正确
	 * @param u
	 * @return	true 正确，false 不正确
	 */
	public boolean login(Users u) {
		boolean flag = false;
		try {
			int count = 0;
			connection = DBUtil.getConnection();
			String sql = "select count(*) as count from users where User_name = ? and password = ?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, u.getUser_name());
			preparedStatement.setString(2, u.getPassword());
			resultSet = preparedStatement.executeQuery();
			while(resultSet.next()) {
				count = resultSet.getInt("count");
			}
			if(count != 0) {
				flag = true;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			closed();
		}
		return flag;
	}
	
	
	
	/**
	 * 添加用户(注册)
	 * @param u
	 * @return	返回修改数据库条数(0 失败 1成功)
	 */
	public int addUser(Users u) {
		int count = 0;
		try {
			connection = DBUtil.getConnection();
			String sql = "insert into users(User_name,Password,Sex) values(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, u.getUser_name());
			preparedStatement.setString(2, u.getPassword());
			preparedStatement.setString(3, u.getSex());
			
			
			count = preparedStatement.executeUpdate();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			closed();
		}
		return count;
	}
	
	
	
	/**
	 * 判断用户名是否存在
	 * @param u
	 * @return	true 存在，false 不存在
	 */
	public boolean isExist(Users u) {
		boolean flag = false;
		try {
			int count = 0;
			connection = DBUtil.getConnection();
			String sql = "select count(*) as count from users where User_name=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, u.getUser_name());
			resultSet = preparedStatement.executeQuery();
			while(resultSet.next()) {
				count = resultSet.getInt("count");
			}
			if(count != 0) {
				flag = true;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			closed();
		}
		return flag;
	}
	
	
	
}
